package org.gwh.airagknowledge.api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.gwh.airagknowledge.entity.KnowledgeBase;
import org.gwh.airagknowledge.repository.KnowledgeBaseRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/knowledge-bases")
@RequiredArgsConstructor
@Tag(name = "Knowledge Base Management", description = "APIs for managing knowledge bases")
public class KnowledgeBaseController {

    private final KnowledgeBaseRepository knowledgeBaseRepository;

    @GetMapping
    @Operation(summary = "Get all knowledge bases", description = "Retrieve a list of all knowledge bases")
    public ResponseEntity<List<KnowledgeBase>> getAllKnowledgeBases() {
        return ResponseEntity.ok(knowledgeBaseRepository.findAll());
    }

    @GetMapping("/{id}")
    @Operation(summary = "Get knowledge base by ID", description = "Retrieve a single knowledge base by its ID")
    public ResponseEntity<KnowledgeBase> getKnowledgeBaseById(@PathVariable Long id) {
        return knowledgeBaseRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    @Operation(summary = "Create knowledge base", description = "Create a new knowledge base")
    public ResponseEntity<KnowledgeBase> createKnowledgeBase(@RequestBody KnowledgeBase knowledgeBase) {
        if (knowledgeBaseRepository.existsByName(knowledgeBase.getName())) {
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(knowledgeBaseRepository.save(knowledgeBase));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "Delete knowledge base", description = "Delete a knowledge base by its ID")
    public ResponseEntity<Void> deleteKnowledgeBase(@PathVariable Long id) {
        if (!knowledgeBaseRepository.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        
        knowledgeBaseRepository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}